package org.modulefusion.dirinstaller.handler;

import org.modulefusion.dirinstaller.AbstractHandler;
import org.modulefusion.dirinstaller.DirInstallerException;
import org.osgi.framework.Bundle;
import org.osgi.framework.BundleContext;
import org.osgi.framework.BundleException;

public class JarFileHandler extends AbstractHandler {

    /**
     * @param context
     */
    public JarFileHandler(BundleContext context) {
        super(context);
    }

    /**
     * @see org.modulefusion.dirinstaller.AbstractHandler#installOrUpdate(java.lang.String, boolean)
     */
    @Override
    public void installOrUpdate(String s, boolean startup) throws DirInstallerException {
        // Check if bundle is already installed
        // Perform bundle update in this case
        for (Bundle b : context.getBundles()) {
            if (b.getLocation().endsWith(s)) {
                if (startup) // Don't update bundles on startup
                    return;
    
                logger.info("Updating bundle '" + b.getSymbolicName() + "'");
                try {
                    b.update();
                } catch (BundleException e) {
                    throw new DirInstallerException("can't update Bundle "+b.getSymbolicName()+" due to "+e.getMessage(), e);
                }
                return;
            }
        }
        // If the bundle is not installed, perform bundle install
        logger.info("Installing bundle: " + s);
        try {
            context.installBundle("file:" + s);
        } catch (BundleException e) {
            throw new DirInstallerException("can't install Bundle "+s+" due to "+e.getMessage(), e);
        }
    }
    
    /**
     * @see org.modulefusion.dirinstaller.AbstractHandler#handles(java.lang.String)
     */
    @Override
    public boolean handles(String fileName) {
        return fileName.endsWith(".jar");
    }
}
